package com.yoofn.nbwk.utils

import android.graphics.Color
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.yoofn.kotlin.base.Constants
import com.yoofn.kotlin.base.GlobalConfig
import com.yoofn.kotlin.utils.SPUtils
import java.util.regex.Pattern

/**
 * 创建人：KalShen
 * 创建时间：2017/2/5 0:46
 * 修改备注：EditText的检测工具
 */


object CheckUtil {

    /**
     * 判断是否为手机号码
     * @param mobiles 手机号码
     */
    fun isMobileNO(mobiles: String): Boolean {

        val p = Pattern

                .compile("^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$")

        val m = p.matcher(mobiles)

        return m.matches()

    }

    /**
     * 判断是否为手机号码
     * @param editText 输入手机号的 EditText
     */
    fun isMobileNO(editText: EditText): Boolean {
        val trim = editText.text.toString().trim { it <= ' ' }
        val p = Pattern

                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$")

        val m = p.matcher(trim)

        if (m.matches()) {
            return true
        } else {
            editText.setHintTextColor(Color.RED)
            editText.hint = "请填写正确的手机号"
            return false
        }

    }

    /**
     * 判断是否符合密码条件
     * @param password 密码
     */
    fun checkPassword(password: String): Boolean {

        val p = Pattern

                .compile("^[a-zA-Z0-9]{${GlobalConfig.PWD_MIN_LENGTH},${GlobalConfig.PWD_MAX_LENGTH}}$")

        val m = p.matcher(password)

        return m.matches()

    }

    /**
     * 判断是否符合密码条件
     * @param editText 输入密码的 EditText
     */

    fun checkPassword(editText: EditText): Boolean {

        val p = Pattern

                .compile("^[a-zA-Z0-9]{${GlobalConfig.PWD_MIN_LENGTH},${GlobalConfig.PWD_MAX_LENGTH}}$")

        if (editText.text.toString().trim { it <= ' ' }.length < GlobalConfig.PWD_MIN_LENGTH) {
            Toast.makeText(editText.context, "密码至少为6位字符", Toast.LENGTH_SHORT).show()
            return false
        }

        val m = p.matcher(editText.text.toString().trim { it <= ' ' })

        val matches = m.matches()

        if (!matches) {
            Toast.makeText(editText.context, "密码必须是6至16位字符或数字", Toast.LENGTH_SHORT).show()
        }
        return true
    }

    /**
     * 判断两次密码是否一致
     */
    fun isPasswordConfirm(password: EditText, passwordConfirm: EditText): Boolean {
        if (TextUtils.equals(password.text, passwordConfirm.text)) {
            return true
        } else {
            Toast.makeText(password.context, "两次密码不一致", Toast.LENGTH_SHORT).show()
            return false
        }
    }

    /**
     * 判断是否为邮箱
     */
    fun isEmail(email: String): Boolean {

        val str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"

        val p = Pattern.compile(str)

        val m = p.matcher(email)

        return m.matches()

    }

    fun isEmail(email: EditText): Boolean {
        val trim = email.text.toString().trim { it <= ' ' }
        val str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"

        val p = Pattern.compile(str)

        val m = p.matcher(trim)
        if (m.matches()) {
            return true
        } else {
            email.setHintTextColor(Color.RED)
            email.hint = "请填写正确的邮箱"
            return false
        }

    }

    /**
     * 判断是否全是数字
     */
    fun isNumeric(str: String): Boolean {

        val pattern = Pattern.compile("[0-9]*")

        val isNum = pattern.matcher(str)

        if (!isNum.matches()) {

            return false

        }

        return true

    }

    /**
     * 判断验证码是否正确
     */
    fun isCodeRight(code: EditText, rightCode: String): Boolean {
        if (rightCode != code.text.toString().trim { it <= ' ' }) {
            Toast.makeText(code.context, "请输入正确的验证码", Toast.LENGTH_SHORT).show()
            return false
        }
        return true
    }

    fun isEmpty(string: String): Boolean {
        return TextUtils.isEmpty(string)
    }

    fun isEmpty(editText: EditText): Boolean {
        val trim = editText.text.toString().trim { it <= ' ' }
        if (TextUtils.isEmpty(trim)) {
            editText.setHintTextColor(Color.RED)
            editText.hint = "输入不为空"
            return true
        } else {
            return false
        }
    }

    /**
     * 判断是否是银行卡号
     * @param cardId
     * *
     * @return
     */
    fun checkBankCard(cardId: String): Boolean {
        val bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length - 1))
        if (bit == 'N') {
            return false
        }
        return cardId[cardId.length - 1] == bit
    }

    private fun getBankCardCheckCode(nonCheckCodeCardId: String?): Char {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim { it <= ' ' }.length == 0
                || !nonCheckCodeCardId.matches("\\d+".toRegex())) {
            // 如果传的不是数据返回N
            return 'N'
        }
        val chs = nonCheckCodeCardId.trim { it <= ' ' }.toCharArray()
        var luhmSum = 0
        var i = chs.size - 1
        var j = 0
        while (i >= 0) {
            var k = chs[i] - '0'
            if (j % 2 == 0) {
                k *= 2
                k = k / 10 + k % 10
            }
            luhmSum += k
            i--
            j++
        }
        return if (luhmSum % 10 == 0) '0' else ((10 - luhmSum % 10) + '0'.toInt()).toChar()
    }

    /**
     * 判断当前验证码是否在发送时间限制内
     */
    fun checkInSmsTimeLimit(textView: TextView) {
        checkTimeInCountdown(textView = textView, triggerTimeInSpName = Constants.SP.SMS_TIME, countdownTime = GlobalConfig.SMS_COUNTDOWN_TIME, endsText = "重新获取验证码", format = "-秒", regex = "-", frequency = 1000)
    }

    /**
     * 判断是否在时间限制内（倒计时）
     * @param textView 出发时间倒计时的textView
     * @param triggerTimeInSpName Sp中保存的出发时间倒计时那一刻的系统时间
     * @param countdownTime 倒计时时长
     * @param endsText 倒计时结束后显示的文字
     * @param format 倒计时格式 例如:剩余-秒
     * @param regex 匹配正则 例如:"-"
     * @param frequency 倒计时频率 每秒递减 还是没分钟递减
     * @param inTimeAction {选填} 在倒计时中的其他action操作
     */
    fun checkTimeInCountdown(textView: TextView, triggerTimeInSpName: String, countdownTime: Int, endsText: String, format: String, regex: String, frequency: Long, inTimeAction:(()->Unit)?=null) {
        val handler = Handler(textView.context.mainLooper)
        val smsTime = SPUtils.getInstance().getLong(triggerTimeInSpName)
        handler.post {
            (countdownTime + smsTime - System.currentTimeMillis()).let {
                textView.isEnabled = false
                if (it > countdownTime || it <= 0) {
                    textView.isEnabled = true
                } else {
                    inTimeAction?.invoke()
                    val split = format.split(regex)
                    val s = split[0] + (it / frequency).toInt().toString() + split[1]
                    textView.text = s
                    textView.isEnabled = false
                    textView.postDelayed(object : Runnable {
                        var time = (it / frequency).toInt()
                        var timeString: String = time.toString()
                        override fun run() {
                            if (time <= 0) {
                                textView.text = endsText
                                textView.isEnabled = true
                                return
                            } else {
                                timeString = split[0] +time.toString() + split[1]
                                textView.text = timeString
                                time -= 1
                                textView.postDelayed(this, frequency)
                            }
                        }
                    }, frequency)
                }
            }
        }
    }


    /**
     * 2017/06/25 添加
     * 动态检测是否满足按钮enable的条件
     * @param root 根布局文件
     * @param btn 要enable 的button
     * @param editText 过滤的editText 数组
     *
     */
    fun checkEnable(root: View, btn: Button, vararg editText: EditText) {
        btn.isEnabled = false
        //遍历子控件 设置输入变化事件
        (0..(root as ViewGroup).childCount - 1)
                .filter { root.getChildAt(it) is EditText }
                .forEach {
                    val childAt = root.getChildAt(it) as EditText
                    childAt.addTextChangedListener(object : TextWatcher {
                        override fun afterTextChanged(s: Editable?) {
                            //先开启enable 以及给flag 为true ，再根据后面条件改变
                            btn.isEnabled = true
                            //遍历子控件 检测是否输入为空
                            (0..root.childCount - 1)
                                    .filter {
                                        val childAt1 = root.getChildAt(it)
                                        childAt1 is EditText && editText.filter { childAt1 == it }.isEmpty()
                                    }
                                    .forEach {
                                        val childAt2 = root.getChildAt(it)
                                        if ((childAt2 as EditText).text.trim().toString().isEmpty()) {  //editText 文本为空则改变flag 为false 关闭enable
                                            btn.isEnabled = false
                                        }
                                    }
                            //TODO 这里是你要enable的button的背景
//                            btn.setBackgroundResource(if (condition) R.drawable.shape_round_radius_50_bg_red else R.drawable.shape_round_radius_50_bg_gray)
                        }

                        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                        }

                        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                        }

                    })
                }
    }
}
